package chances.epg.api.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import chances.epg.commons.controller.ApiExceptionHandleResolver;

@Configuration
@ComponentScan(basePackages = "chances.epg.api.controller,chances.epg.navigator.service")
@PropertySource("/WEB-INF/conf/epg.properties")
public class EpgApiMvcConfig extends WebMvcConfigurationSupport {
	@Value("${epg.resource.root:/resource}")
	private String resourcePath;

	@Value("${epg.server.url}")
	private String epgHost;

	@Bean
	ApiExceptionHandleResolver exceptionResolver() {
		return new ApiExceptionHandleResolver();
	}

	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		super.addCorsMappings(registry);
		registry.addMapping("/**").allowedOrigins("*").allowedMethods("PUT", "DELETE", "POST", "GET")
				.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
						"Access-Control-Request-Headers")
				.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
				.allowCredentials(true).maxAge(3600);
	}

	@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setViewClass(JstlView.class);
		resolver.setPrefix("/WEB-INF");
		return resolver;
	}
	
	@Bean
	public EpgApiConfigUtils getEpgApiConfigUtils() {
		EpgApiConfigUtils epgApiConfigUtils = EpgApiConfigUtils.getInstance();
		epgApiConfigUtils.setEpgServer(this.epgHost);
		epgApiConfigUtils.setImageServer(this.resourcePath);
		return epgApiConfigUtils;
	}

	public String getResourcePath() {
		return resourcePath;
	}

	public void setResourcePath(String resourcePath) {
		this.resourcePath = resourcePath;
	}

	public String getEpgHost() {
		return epgHost;
	}

	public void setEpgHost(String epgHost) {
		this.epgHost = epgHost;
	}
}
